package com.shi.websocketspringboot.service;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description TODO
 * @Author User Name
 * @Date 2020-11-11 15:57
 **/
@ServerEndpoint("/webSocket/{userId}")
@Component
public class WebSocketService {

    private static AtomicInteger atomicInteger=new AtomicInteger(0);
    private static ConcurrentHashMap<String ,Session>sessionPools=new ConcurrentHashMap<>();


    //在线人数加一
    private static void addOnlineCount(){
        atomicInteger.incrementAndGet();
    }
    //在线人数减一
    private static void subOnlineCount(){
        atomicInteger.decrementAndGet();
    }

    //发送消息
    public void sendMessage(Session session,String message) throws IOException {
        if (session!=null){
            synchronized (session){
                session.getBasicRemote().sendText(message);
            }
        }
    }
    //给指定用户发送消息
    public void sendInfo(String userId,String message){
        Session session=sessionPools.get(userId);
        try {
            sendMessage(session,message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId")String userId){
        sessionPools.put(userId,session);
        addOnlineCount();
        sendInfo(userId,"欢迎"+userId+"加入连接");

        System.out.println("开启现在连接数为:"+atomicInteger);
    }
    @OnClose
    public void onClose(@PathParam("userId") String userId){
        sessionPools.remove(userId);
        subOnlineCount();
        System.out.println("关闭现在连接数为:"+atomicInteger);
    }

    @OnMessage
    public void onMessage(String message) {
        message="客户端："+ message+",已收到";
        System.out.println(message);
        for (Session session : sessionPools.values()){
            try {
                sendMessage(session,message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("发送错误");
        throwable.printStackTrace();
    }
}
